package cn.hongpeiming.videodanmakusite.controller;

import cn.hongpeiming.videodanmakusite.mapper.ComplaintMapper;
import cn.hongpeiming.videodanmakusite.mapper.DanmakuMapper;
import cn.hongpeiming.videodanmakusite.pojo.*;
import cn.hongpeiming.videodanmakusite.service.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Array;
import java.util.*;

@Controller
public class DanmakuController {
    @Autowired
    DanmakuService danmakuService;
    @Autowired
    UserService userService;
    @Autowired
    ComplainttypeService complainttypeService;
    @Autowired
    ShieldService shieldService;
    @Autowired
    DanmakuMapper danmakuMapper;
    @Autowired
    ComplaintService complaintService;
    @Autowired
    BanKeywordService banKeywordService;

    //测试页面
    @RequestMapping("/SendTestPage")
    public String senddanmakupage()
    {

        return "sendtest";
    }
    //测试用
    @RequestMapping("/SendTest")
    @ResponseBody
    public String  SendTest(Integer DanmakuVideoid, Integer DanmakuVideotime,
                               String DanmakuContent, String DanmakuColor,
                               Integer DanmakuType,
                               HttpSession session, Model model)
    {

        try {

        }catch (Exception e)
        {
            return null;
        }

        cn.hongpeiming.videodanmakusite.pojo.Danmaku danmaku = new Danmaku();
        danmaku.setDanmakuVideoid(DanmakuVideoid);
        danmaku.setDanmakuVideotime(DanmakuVideotime);
        danmaku.setDanmakuContent(DanmakuContent);
        danmaku.setDanmakuColor(DanmakuColor);
        danmaku.setDanmakuType(DanmakuType);
        String JsonDanmaku = JSON.toJSONString(danmaku);
        System.out.println(JsonDanmaku);
        return JsonDanmaku;
    }


    @RequestMapping("/SendDanmaku")
    @ResponseBody
    public String  sendDanmaku(Integer DanmakuVideoid, Integer DanmakuVideotime,
                               String DanmakuContent, String DanmakuColor,
                               Integer DanmakuType,Integer DanmakuSize,
                               HttpSession session, Model model)
    {

        cn.hongpeiming.videodanmakusite.pojo.Danmaku danmaku = new Danmaku();
        try {
            User user = userService.selectUserByUserId((Integer) session.getAttribute("LoginUserId"));
            danmaku.setDanmakuSenderid(user.getUserId());
        }catch (Exception e)
        {
            //return null;
            danmaku.setDanmakuSenderid(0);
        }


        danmaku.setDanmakuVideoid(DanmakuVideoid);
        danmaku.setDanmakuVideotime(DanmakuVideotime);
        danmaku.setDanmakuStringTime();

        danmaku.setDanmakuContent(DanmakuContent);
        danmaku.setDanmakuColor(DanmakuColor);
        danmaku.setDanmakuType(DanmakuType);
        danmaku.setDanmakuSendtime(new Date());
        danmaku.setDanmakuFontsize(16);
        danmaku.setDanmakuStatus(0);
        danmaku.setDanmakuId(danmakuMapper.insert(danmaku));
        String JsonDanmaku = JSON.toJSONString(danmaku);
        System.out.println("JsonDanmaku  :  "+JsonDanmaku);

        return JsonDanmaku;
    }




    //举报页面
    @RequestMapping("/report/{danmakuId}")
    public String ReportPage(@PathVariable("danmakuId")Integer danmakuId,Model model)
    {
        Danmaku danmaku = danmakuService.getDanmakuById(danmakuId);
        model.addAttribute("danmaku",danmaku);

        List<Complainttype> complainttypes = complainttypeService.getAllComplainttype();
        model.addAttribute("complainttypes",complainttypes);

        return "include/report";
    }



    //添加屏蔽
    @RequestMapping("/AddShieldDanmaku/{danmakuId}")
    @ResponseBody
    public String AddShieldDanmaku(@PathVariable("danmakuId")Integer danmakuId,HttpSession session)
    {
        int LoginUserId = 0;
        try {
            LoginUserId = (int) session.getAttribute("LoginUserId");

        }catch (Exception e)
        {
            System.out.println("没有登录用户");
            return "failed";
        }
        shieldService.addShieldDanmaku(danmakuId,LoginUserId);

        return "successed";
    }
    //移除屏蔽
    @RequestMapping("/removeShieldDanmaku/{danmakuId}")
    @ResponseBody
    public String removeShieldDanmaku(@PathVariable("danmakuId")Integer danmakuId,HttpSession session)
    {
        int LoginUserId = 0;
        try {
            LoginUserId = (int) session.getAttribute("LoginUserId");

        }catch (Exception e)
        {
            System.out.println("没有登录用户");
            return "failed";
        }
        shieldService.DeleteShieldDanmaku(danmakuId,LoginUserId);

        return "successed";
    }


    //提交弹幕举报
    @RequestMapping("/PostComplaintDanmaku/{danmakuId}")
    @ResponseBody
    public String PostComplaintDanmaku(@PathVariable("danmakuId")Integer danmakuId,Integer complainttype,String complaintContext,HttpSession session)
    {
        int LoginUserId = 0;
        try {
            LoginUserId = (int) session.getAttribute("LoginUserId");

        }catch (Exception e)
        {
            System.out.println("没有登录用户");
            return "failed";
        }
        if (complaintService.isComplainted(danmakuId,LoginUserId))
            return "repeat";

        if (danmakuService.checkDanmakuStatus(danmakuId))
            return "ban";
        Complaint complaint = new Complaint();
        complaint.setComplaintDanmakuId(danmakuId);
        complaint.setComplaintUserId(LoginUserId);
        complaint.setComplaintType(complainttype);
        complaint.setComplaintDescribe(complaintContext);
        complaint.setComplaintStatus(0);
        complaintService.addComplaint(complaint);

        return "successed";
    }

    //撤销弹幕举报
    @RequestMapping("/removeComplaint/{complaintId}")
    @ResponseBody
    public String removeComplaintDanmaku(@PathVariable("complaintId")Integer complaintId,HttpSession session)
    {
        int LoginUserId = 0;
        try {
            LoginUserId = (int) session.getAttribute("LoginUserId");

        }catch (Exception e)
        {
            System.out.println("没有登录用户");
            return "failed";
        }
        complaintService.removeComplaint(complaintId);

        return "successed";
    }

    //设置弹幕状态
    @RequestMapping("/setDanmakuStatus/{danmakuId}/{danmakuStatus}")
    @ResponseBody
    public String SetDanmakuStatus(@PathVariable("danmakuId")Integer danmakuId,@PathVariable("danmakuStatus")Integer danmakuStatus,HttpSession session)
    {
//        int LoginUserId = 0;
        try {
//          LoginUserId = (int) session.getAttribute("LoginUserId");
            danmakuService.switchTheDanmakuStatus(danmakuId,danmakuStatus);
        }catch (Exception e)
        {
//          System.out.println("没有登录用户");
            System.out.println(e);
            return "failed";
        }
        return "successed";
    }


    //添加屏蔽词
    @RequestMapping("/addBanKeyword/{banKeyword}")
    @ResponseBody
    public String addBanKeyword(@PathVariable("banKeyword")String banKeyword,HttpSession session)
    {
        int LoginUserId = 0;

        try {
            LoginUserId = (int) session.getAttribute("LoginUserId");
            if (banKeywordService.repeatBanKeyword(banKeyword,LoginUserId))
                return "repeat";
            banKeywordService.addBanKeyword(banKeyword,LoginUserId);
        }catch (Exception e)
        {
//          System.out.println("没有登录用户");
            System.out.println(e);
            return "failed";
        }
        int banKey = banKeywordService.findKeywordKey(banKeyword,LoginUserId);
        return banKey+"";
    }
    //添加屏蔽词
    @RequestMapping("/removeBanKeyword/{banKeywordId}")
    @ResponseBody
    public String removeBanKeyword(@PathVariable("banKeywordId")Integer banKeywordId,HttpSession session)
    {
        try {
            banKeywordService.removeBankeyword(banKeywordId);
        }catch (Exception e)
        {
//          System.out.println("没有登录用户");
            System.out.println(e);
            return "failed";
        }
        return "successed";
    }



    //视频页面所需数据 Json获取
    @RequestMapping("/getDanmakuData/{videoId}.json")
    @ResponseBody
    @CrossOrigin
    public String getDanmakuData(@PathVariable("videoId")Integer videoId,HttpSession session)
    {
        List<Danmaku> danmakus = danmakuService.getUnBanDanmakuByVideoId(videoId);
        ArrayList<Object> DanmakuData = new ArrayList<Object>();
        DanmakuData.add(danmakus);
        int LoginUserId = 0;

        try {
            LoginUserId = (int) session.getAttribute("LoginUserId");
            //获取屏蔽词和屏蔽弹幕
            List<Shield> shields = shieldService.getVideoShieldDanmaku(LoginUserId);
            DanmakuData.add(shields);
            List<BanKeyword> banKeywords = banKeywordService.findMyBankeyword(LoginUserId);
            DanmakuData.add(banKeywords);
        }catch (Exception e)
        {
//          System.out.println("没有登录用户");
            System.out.println(e);
        }
        String JsonDanmakuData = JSON.toJSONString(DanmakuData);
        return JsonDanmakuData;
    }



    //分页查询
    @RequestMapping("/getDanmakuDataPage/{videoId}")
    @ResponseBody
    public String getDanmakuPage(@PathVariable("videoId")Integer videoId, @RequestParam("page") Integer page, HttpSession session)
    {


        return "";
    }

    @RequestMapping("/sendDanmakuByUrl/{videoId}")
    @ResponseBody
    public String sendDanmakuByUrl(@PathVariable("videoId")Integer videoId,String danmu, HttpSession session)
    {

        System.out.println("弹幕信息:"+danmu);
        JSONObject jsonDanmaku = JSONObject.parseObject(danmu);
        Danmaku danmaku = new Danmaku();
        danmaku.setDanmakuVideoid(videoId);
        danmaku.setDanmakuVideotime(jsonDanmaku.getInteger("time"));
        danmaku.setDanmakuContent(jsonDanmaku.getString("text"));
        danmaku.setDanmakuColor(jsonDanmaku.getString("color"));
        danmaku.setDanmakuType(jsonDanmaku.getInteger("position"));
        danmaku.setDanmakuFontsize(jsonDanmaku.getInteger("size"));
        danmaku.setDanmakuSendtime(new Date());
        danmaku.setDanmakuStatus(0);
        //jsDanmaku jsDm = (jsDanmaku)JSON.parse(danmu);
        //System.out.println("对象==="+jsDm.toString());
        try {
            User user = userService.selectUserByUserId((Integer) session.getAttribute("LoginUserId"));
            danmaku.setDanmakuSenderid(user.getUserId());
        }catch (Exception e)
        {
            //return null;
            danmaku.setDanmakuSenderid(0);
        }
        System.out.println(danmaku.toString());
        danmakuService.sendDanmaku(danmaku);
        return "";
    }
    @RequestMapping("/getDanmakuDataByUrl/{videoId}")
    @ResponseBody
    public String getDanmakuDataByUrl(@PathVariable("videoId")Integer videoId, HttpSession session)
    {
        List<Danmaku> danmakus = danmakuService.getUnBanDanmakuByVideoId(videoId);
        ArrayList<Danmaku> danmakuArrayList = new ArrayList<>();
        int LoginUserId = 0;
        try {
            LoginUserId = (int) session.getAttribute("LoginUserId");
            //获取屏蔽词和屏蔽弹幕
            List<Shield> shields = shieldService.getVideoShieldDanmaku(LoginUserId);
            List<BanKeyword> banKeywords = banKeywordService.findMyBankeyword(LoginUserId);
            for (Danmaku danmaku:danmakus)
            {
                Boolean b = true;
                for (Shield shield:shields)
                {
                    if (danmaku.getDanmakuId().equals(shield.getShieldBanid()))
                    {
                        b = false;
                    }
                }
                for (BanKeyword banKeyword:banKeywords)
                {
                    if (danmaku.getDanmakuContent().contains(banKeyword.getBanKeywordString()))
                    {
                        b = false;
                    }
                }
                if (b)
                {
                    danmakuArrayList.add(danmaku);
                }
            }

        }catch (Exception e)
        {
          System.out.println("没有登录用户");
          System.out.println(e);
          danmakuArrayList = (ArrayList<Danmaku>) danmakus;
        }


//        Map<Integer, ArrayList<jsDanmaku>> danmakuMap = new HashMap<Integer,ArrayList<jsDanmaku>>();
//        for (Danmaku danmaku:danmakuArrayList)
//        {
//            jsDanmaku jsDm = new jsDanmaku();
//            jsDm.setText(danmaku.getDanmakuContent());
//            jsDm.setColor(danmaku.getDanmakuColor());
//            jsDm.setPosition(danmaku.getDanmakuType());
//            jsDm.setSize(danmaku.getDanmakuFontsize());
//            if (danmakuMap.containsKey(danmaku.getDanmakuVideotime()))
//            {
//                danmakuMap.get(danmaku.getDanmakuVideotime()).add(jsDm);
//                //jsDanmakus.add(jsDm);
//            }else {
//                ArrayList<jsDanmaku> jsDanmakus = new ArrayList<>();
//                jsDanmakus.add(jsDm);
//                danmakuMap.put(danmaku.getDanmakuVideotime(),jsDanmakus);
//            }
//        }

        ArrayList<jsDanmaku_v2> jsDanmakuV2s = new ArrayList<>();
        for (Danmaku danmaku:danmakuArrayList)
        {
            jsDanmaku_v2 jsDmV2 = new jsDanmaku_v2();
            jsDmV2.setText(danmaku.getDanmakuContent());
            jsDmV2.setColor(danmaku.getDanmakuColor());
            jsDmV2.setPosition(danmaku.getDanmakuType());
            jsDmV2.setSize(danmaku.getDanmakuFontsize());
            jsDmV2.setTime(danmaku.getDanmakuVideotime());
            jsDanmakuV2s.add(jsDmV2);
        }



        return JSON.toJSONString(jsDanmakuV2s);
    }

}
